import re
from rest_framework.views import APIView
from mexam import models, serializer
from rest_framework.response import Response
from utils.jwttool import meansjwt
from rest_framework.viewsets import ViewSet, ModelViewSet
from rest_framework.pagination import PageNumberPagination
import django_filters
from utils.redis import redistool
from django.core.files.storage import default_storage


# Create your views here.

class loginin(APIView):
    def post(self, request):
        name = request.data.get('name')
        password = request.data.get('password')
        if not name or not password:
            return Response({'msg': '必传用户名或者密码'})
        info = models.examuser.objects.filter(name=name).first()
        if not info:
            return Response({'msg': '无效的用户'})
        else:
            if info.password != password:
                return Response({'msg': '密码错误'})
            userinfo = {"id": info.id}
            token = meansjwt.gettoken(userinfo)
            return Response({'msg': '登录成功', "code": 200, "token": token})


class listpagination(PageNumberPagination):
    page_size = 5
    page_size_query_param = "size"


class bookfilter(django_filters.rest_framework.FilterSet):
    title = django_filters.CharFilter(field_name='title', lookup_expr="icontains")

    class Meta:
        model = models.book
        fields = ["title", "status", "author", "booktype"]


class book(ModelViewSet):
    serializer_class = serializer.booklist
    queryset = models.book.objects.all()
    pagination_class = listpagination
    filter_backends = [django_filters.rest_framework.DjangoFilterBackend]  # 配置过滤器(要不全局设置  )
    filterset_class = bookfilter


class booktype(ModelViewSet):
    serializer_class = serializer.booktype
    queryset = models.booktype.objects.all()


class author(ModelViewSet):
    serializer_class = serializer.author
    queryset = models.author.objects.all()


class deleteid(APIView):
    def get(self, request):
        id = request.query_params.get("id")
        models.book.objects.filter(id=id).delete()
        return Response({"msg": "删除成功"})


class changestatus(APIView):
    def get(self, request):
        id = request.query_params.get("id")
        info = models.book.objects.filter(id=id).first()
        info.status = not info.status
        info.save()
        redistool.set_info(id)
        return Response({"msg": "修改成功", "data": redistool.get_info()})
